<?php
/**
 * 文件上传输入域[修正]
 * <pre>
 * <input type='file' name='attribute'>
 * <input type='hidden' name='attribute'>
 * </pre>
 * 解决了update时显示attribute cannot be blank的错误。
 * <br><br>控件需要配合其他的组件组合使用，才能达到理想效果，以下是一个完整的示例。
 * 在model中，配置{@link CFileSaveBehavior CFileSaveBehavior}，和rules：
 * <pre>
 * // 属性：缩略图附件
 * public $thumb;
 * // other attributes.
 * ...
 * function behaviors() {
 *  'fileSaver' => array(
 *   'class' => 'lib.behaviors.ar.CFileSaveBehavior',
 *   'basePath' => dirname(Yii::app()->basePath).'/uploaded',
 *   'baseUrl' => Yii::app()->baseUrl.'/uploaded',
 *   'attributes' => array('thumb'),
 *  )
 *  ...
 *  function rules() {
 *   return array(
 *    array('thumb', 'file', 'allowEmpty'=>true, 'types'=>'jpg, gif, bmp, png'),
 *    // 如果要使用必填验证的话，不要设置allowEmpty为false
 *    // 而是使用required验证器，如下
 *    array('thumb', 'required'),
 *   );
 *  }
 * }
 * </pre>
 * 输入域配置
 * <pre>
 * $this->widget('lib.widgets.CActiveFileField', array(
 *  'form' => $form,
 *  'model' => $model,
 *  'attribute' => 'thumb',
 * ))
 * </pre>
 * @author yangdongqi <yangdongqi@hayzone.com>
 * @package lib.widgets
 */
class CActiveFileField extends CWidget {
	
	public $form;
	public $model;
	public $attribute;
	public $htmlOptions;
	
	public function run() {
		if($this->form instanceof CActiveFormAdv) {
			list($model, $attribute, $htmlOptions) = 
				$this->form->resolveArgs($this->model, $this->attribute, $this->htmlOptions);
		} else {
			CHtml::resolveNameID($this->model, $this->attribute, $this->htmlOptions);
			$model = $this->model;
			$attribute = $this->attribute;
			$htmlOptions = $this->htmlOptions;
		}
		
		$hiddenHtmlOptions = array();
		foreach(array('name', 'id') as $k) {
			if(isset($htmlOptions[$k])) {
				$hiddenHtmlOptions[$k] = $htmlOptions[$k];
			}
		}
		$htmlOptions['id'] = empty($htmlOptions['id']) ? uniqid() : $htmlOptions['id'];
		echo CHtml::fileField($htmlOptions['name'], '', $htmlOptions)
			.CHtml::activeHiddenField($model, $attribute, $hiddenHtmlOptions);
		
	}
	
}

?>